import operate from '@dfeidao/atom-nodejs/db/operate';
// import query from '@dfeidao/atom-nodejs/db/query';
import log from '@dfeidao/atom-nodejs/logger/log';

interface Message {
	productid: string;
	level_no: string;
	newarr: Array<{
		left: {
			client_type: string
			productid: string;
			formid: string;
			formname: string;
			level_no: string;
			group_number: string;
		}; right: Array<{
			action_name: string,
			formid: string,
			action_keyword: string,
			code: string,
			productid: string
		}>
	}>;
	client_type: string;
}

export default async function atom(msg: Message, action_id: string, session_id: string) {
	log('Service begin');
	// todo
	const { del, insert, exec } = operate(action_id, session_id, '12');
	del('tenant_level_form', { productid: msg.productid, level_no: msg.level_no, client_type: msg.client_type });
	// return msg.newarr;
	msg.newarr.forEach((v) => {
		if (v.left.formid) {
			del('tenant_level_form_code', { productid: msg.productid, formid: v.left.formid });
			insert('tenant_level_form', { client_type: v.left.client_type, level_no: v.left.level_no, formid: v.left.formid, formname: v.left.formname, productid: msg.productid, group_number: v.left.group_number });
			v.right.forEach((item) => {
				insert('tenant_level_form_code', {
					action_name: item.action_name,
					formid: item.formid,
					action_keyword: item.action_keyword,
					code: item.code,
					productid: msg.productid,
					level_no: v.left.level_no
				});
			});
		}
	});
	const ret = await exec();
	log('Service end');
	if (ret.code === 1) {
		return 'success';
	} else {
		return 'fail';
	}
}
